package com.appspot.battlerafts.servlets.user;

import com.appspot.battlerafts.classes.Game;
import com.appspot.battlerafts.classes.User;
import com.appspot.battlerafts.enums.GameState;
import com.appspot.battlerafts.jsons.GameDataJSON;
import com.appspot.battlerafts.utils.PMF;
import com.google.gson.Gson;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.appspot.battlerafts.utils.Util.returnError;
import static com.appspot.battlerafts.utils.Util.returnSuccess;

/**
 * Created with IntelliJ IDEA.
 * User: Tonis
 * Date: 02.04.12
 * Time: 14:43
 * To change this template use File | Settings | File Templates.
 */
public class MarkUserOffline extends HttpServlet {
    private static final Logger log = Logger.getLogger(MarkUserOffline.class.getName());
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Gson gson = new Gson();
        log.setLevel(Level.INFO);
        log.info("OFFLINE");
        log.info(request.getParameter("data"));
        GameDataJSON gameDataJSON = gson.fromJson(request.getParameter("data"), GameDataJSON.class);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        User user;
        try {
            user = pm.getObjectById(User.class, gameDataJSON.playerUID);
            user.setOnline(false);
            Query q = pm.newQuery(Game.class);
            q.setFilter("initator == " + user.getUID() + " && (gameState == '" + GameState.WAITING.toString() + "' || gameState == '" + GameState.RUNNING.toString() + "')");
            List<Game> gamesWhereInitator = (List<Game>) q.execute();
            log.info("FOUND THESE GAMES WHERE INITATOR and state RUNNING || WAITING: " + gamesWhereInitator);
            pm.deletePersistentAll(gamesWhereInitator);
        } catch (JDOObjectNotFoundException e) {
            returnError(response, "The user with ID " +  gameDataJSON.playerUID + " was not found from database");
            return;
        } finally {
            pm.close();
        }

        returnSuccess(response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
